﻿using System;
using System.Collections.Generic;
using System.IO;

namespace DalamudManager.Models
{
    public static class PluginList
    {
        static string PluginFolderPath => Path.Combine(MainWindow.Current?.Config?.DalamudPath, "XIVLauncher/installedPlugins");

        public static PluginInfo[] List { get; private set; }

        public static void Update(Action callback = null)
        {
            var pluginFolder = new DirectoryInfo(PluginFolderPath);
            if (pluginFolder.Exists)
            {
                var list = pluginFolder.GetDirectories();
                List<PluginInfo> records = new();
                foreach (var plugin in list)
                {
                    var info = GetPluginInfo(plugin);
                    if (info != null)
                        records.Add(info);
                }
                List = records.ToArray();
                callback?.Invoke();
            }
        }

        public static DirectoryInfo GetPluginFolder(string pluginName)
            => new DirectoryInfo(Path.Combine(PluginFolderPath, pluginName));

        public static PluginInfo GetPluginInfo(string pluginName)
            => GetPluginInfo(GetPluginFolder(pluginName));
        public static PluginInfo GetPluginInfo(DirectoryInfo pluginFolder)
        {
            if (pluginFolder.Exists)
            {
                var search = pluginFolder.GetFiles("*.dll", SearchOption.AllDirectories);
                if (search.Length <= 0)
                    return null;
                var file = search[0];
                bool isDisable = new FileInfo(Path.Combine(file.Directory.FullName, ".disabled")).Exists;
                var def = new FileInfo(Path.Combine(file.Directory.FullName,
                    Path.GetFileNameWithoutExtension(file.Name) + ".json"));
                if (!def.Exists)
                    return null;
                var result = PluginInfo.Parse(File.ReadAllText(def.FullName));
                result.IsDisable = isDisable;
                result.Path = file.Directory.FullName;
                return result;
            }
            return null;
        }
    }
}
